﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace FusionDotNet
{
    /// <summary>
    /// Retrieves the schema for the specified table. Use the <see cref="ListTablesCommand"/> to return a list of table identifiers.
    /// </summary>
    public class DescribeTableCommand : GetCommand<SelectResult>
    {
        private const string COMMAND = "DESCRIBE";
        private int m_TableId;

        /// <summary>
        /// Construct a DescribeTableCommand/
        /// </summary>
        /// <param name="tableId">Id of the table to describe.</param>
        public DescribeTableCommand(int tableId)
        {
            m_TableId = tableId;
        }

        /// <summary>
        /// Sets the Query string for the Command.
        /// </summary>
        /// <returns>String to use as the Query string.</returns>
        protected override string GetCommandQueryString()
        {
            return string.Format("{0} {1}",COMMAND, m_TableId);
        }

        /// <summary>
        /// Converts the stream containing the query results to a <see cref="SelectResult"/>.
        /// </summary>
        /// <param name="reader"><see cref="StreamReader"/> containing the result of the query.</param>
        /// <returns><see cref="SelectResult"/> containing the results of the query.</returns>
        internal override SelectResult CreateResult(StreamReader reader)
        {
            using (DataTable dataTable = new DataTable(m_TableId.ToString()))
            {
                string[] headers = reader.ReadLine().Split(',');
                while (!reader.EndOfStream)
                {
                    string[] tableInfo = reader.ReadLine().Split(',');
                    dataTable.Columns.Add(tableInfo[1], TableBuilder.ConvertToType(tableInfo[2]));
                }
                return new SelectResult(dataTable);
            }
        }

    }
}
